package com.baidu.process.chat.parser.sourceHandler.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.process.chat.core.action.Actions;
import com.baidu.process.chat.core.web.bean.IMRequestServer;
import com.baidu.process.chat.parser.bean.QueryJsonStr;
import com.baidu.process.chat.parser.sourceHandler.BaseSourceHandler;
import com.baidu.process.config.service.OptAnswerService;
import com.baidu.process.constant.OptEventEnum;
import com.baidu.process.ngd.bean.NGDResBody;
import com.baidu.process.record.bean.DialogueRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.baidu.process.constant.RedisKey.ClarfyKey;

/**
 * @Author:fangyuchao
 * @Description:
 * @Date: Create in 15:53 2022/11/10
 */
@Service
public class TableHandler implements BaseSourceHandler {
    @Value("${table.car.map}")
    private String tableCarMapStr;
    @Autowired
    private OptAnswerService optAnswerService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public QueryJsonStr handleQuery(NGDResBody ngdResBody, IMRequestServer imRequestServer, DialogueRecord dialogueRecord) {
        String otherText ="";
        QueryJsonStr queryJsonStr = new QueryJsonStr();
        NGDResBody.NGDQueryData  queryData = ngdResBody.getData();
        Map<String,Object> answer = queryData.getAnswer();
        List<Object> answerContents = JSONObject.parseObject(JSONObject.toJSONString(answer.get("answerContents")), List.class);
        String listText="";
        String title="";
        for (Object o :answerContents ){
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o));
            //如果title字段没有，则表示是精确命中taq答案
            Object titleObj = jsonObject.get("title");
            if (titleObj==null){
                listText=answer.get("answerText").toString();
                break;
            }
            title = titleObj.toString();
            //title字段有值就增加换行
            if (StringUtils.isEmpty(title)){
                title=title+"\n";
            }
            List<String> list = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("list")),List.class);
            listText=listText+list.stream().collect(Collectors.joining("\n"));

        }
        otherText = otherText(ngdResBody,listText);
        String sessionId = queryData.getSessionId();
        //重置澄清次数
        redisTemplate.opsForValue().set(ClarfyKey+sessionId,"0",10, TimeUnit.MINUTES);
        queryJsonStr.setSessionId(queryData.getSessionId());
        queryJsonStr.setSource(queryData.getSource());
        //按格式塞
        queryJsonStr.setContext(queryData.getContext());
        queryJsonStr.setAnswer(title+listText+"\n"+otherText);
        queryJsonStr.setBot(Actions.DEFAULT.getCode());
        queryJsonStr.setSource(queryData.getSource());
        return queryJsonStr;
    }

    /**
     * 获取拼接话术
     * @return
     */
    private String otherText(NGDResBody ngdResBody,String listText){
        Map<String,String> tableCarMap = JSONObject.parseObject(tableCarMapStr,Map.class);
        String otherText = "";
        NGDResBody.NGDQueryData  queryData = ngdResBody.getData();
        Map<String,Object> debug = queryData.getDebug();
        Object detailObj = debug.get("detail");
        Map<String,Object> detail = JSONObject.parseObject(JSONObject.toJSONString(detailObj),Map.class);
        String clarify = detail.get("clarify").toString();
        //表格澄清的清情况下拼接澄清话术
        if ("true".equals(clarify)){
            return optAnswerService.getAnswerByEvent(OptEventEnum.tableAnything.name());
        }
        String tableName = detail.get("tableName").toString();
        List<String> propertyNames = JSONObject.parseObject(JSONObject.toJSONString(detail.get("propertyNames")),List.class);
        switch (tableName){
            //车型
            case "cars":
                for (String key: tableCarMap.keySet()){
                    if (listText.contains(key)){
                        return optAnswerService.getAnswerByEvent(OptEventEnum.tableCar.name())+tableCarMap.get("key");
                    }
                }
                return optAnswerService.getAnswerByEvent(OptEventEnum.tableDefault.name());
             //经销商
            case "dealer":
                return optAnswerService.getAnswerByEvent(OptEventEnum.tableDealer.name());
            default:
                return optAnswerService.getAnswerByEvent(OptEventEnum.tableDefault.name());
        }
    }
}
